/*
 *  Copyright 2004 Blandware (http://www.blandware.com)
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.blandware.atleap.webapp.action.core.applicationResource;

import com.blandware.atleap.service.exception.BeanNotFoundException;
import com.blandware.atleap.webapp.action.core.BaseAction;
import com.blandware.atleap.webapp.form.core.ApplicationResourceForm;
import com.blandware.atleap.webapp.util.core.ApplicationResources;
import com.blandware.atleap.webapp.util.core.WebappConstants;
import org.apache.commons.validator.GenericValidator;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.springframework.orm.ObjectOptimisticLockingFailureException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Iterator;
import java.util.Map;

/**
 * <p>Updates application resource
 * </p>
 * <p><a href="UpdateApplicationResourceAction.java.html"><i>View Source</i></a></p>
 * <p/>
 *
 * @author Sergey Zubtsovskiy <a href="mailto:sergey.zubtsovskiy@blandware.com">&lt;sergey.zubtsovskiy@blandware.com&gt;</a>
 * @version $Revision: 1.10 $ $Date: 2006/08/03 10:07:47 $
 * @struts.action name="applicationResourceForm"
 * path="/core/applicationResource/update"
 * scope="request"
 * input="inputForward"
 * validate="true"
 * roles="core-applicationResource-update"
 * @struts.action-forward name="inputForward"
 * path=".core.applicationResource.update"
 * @struts.action-forward name="listApplicationResources"
 * path="/core/applicationResource/list.do"
 * redirect="true"
 * @struts.action-forward name="callUpdateApplicationResource"
 * path="/core/applicationResource/callUpdate.do"
 * redirect="false"
 * @struts.action-forward name="unsatisfiable"
 * path="/core/applicationResource/list.do"
 */
public final class UpdateApplicationResourceAction extends BaseAction {
	/**
	 * @param mapping  The ActionMapping used to select this instance
	 * @param form     The optional ActionForm bean for this request (if any)
	 * @param request  The HTTP request we are proceeding
	 * @param response The HTTP response we are creating
	 * @return an ActionForward instance describing where and how
	 *         control should be forwarded, or null if response
	 *         has already been completed
	 */
	public ActionForward execute(ActionMapping mapping, ActionForm form,
	                             HttpServletRequest request, HttpServletResponse response) throws Exception {

		if ( !isCancelled(request) ) {
			ApplicationResourceForm applicationResourceForm = (ApplicationResourceForm) form;
			String key = applicationResourceForm.getKey();
			if ( GenericValidator.isBlankOrNull(key) ) {
				if ( log.isWarnEnabled() ) {
					log.warn("Missing application resource key. Returning to list...");
				}
				return mapping.findForward("listApplicationResources");
			}

			Map valueMap = applicationResourceForm.getValueMap();

			boolean resourceExists = true;
			boolean alreadyUpdatedExist = false;
			ApplicationResources applicationResources = ApplicationResources.getInstance(servlet.getServletContext());
			for ( Iterator i = valueMap.entrySet().iterator(); i.hasNext(); ) {
				Map.Entry entry = (Map.Entry) i.next();
				String localeIdentifier = (String) entry.getKey();
				String value = (String) entry.getValue();

                String versionString = (String)applicationResourceForm.getVersion(localeIdentifier);
                Long version;
                if (GenericValidator.isBlankOrNull(versionString)) {
                    version = null;
                } else {
                    version = Long.valueOf(versionString);
                }
                try {
					applicationResources.updateResource(localeIdentifier, key, value, version);
				} catch ( BeanNotFoundException e ) {
                    resourceExists = false;
				} catch ( ObjectOptimisticLockingFailureException e ) {
					// action page was updated by another transaction
					alreadyUpdatedExist = true;
				}
			}

			if ( !resourceExists ) {
				// some resource not found. it might be deleted by someone else
				ActionMessages errors = new ActionMessages();
				errors.add("applicationResourceNotFound", new ActionMessage("core.applicationResource.errors.notFound", key));
				saveErrors(request, errors);
				return mapping.findForward("listApplicationResources");
			}

			if ( alreadyUpdatedExist ) {
				ActionMessages errors = new ActionMessages();
				errors.add("updateFailed", new ActionMessage("core.applicationResource.errors.updateFailed"));
				saveErrors(request, errors);
				request.setAttribute(WebappConstants.APPLICATION_RESOURCE_KEY_KEY, key);
				return mapping.findForward("callUpdateApplicationResource");
			}

		}
		return mapping.findForward("listApplicationResources");
	}
}